using System;
using System.Threading.Tasks;

namespace GomokuGame.AI
{
    /// <summary>
    /// AI管理器
    /// </summary>
    public class AIManager
    {
        private IAIAlgorithm currentAI;
        private bool isAITurn = false;
        private int maxThinkingTime = 5000;

        /// <summary>
        /// AI思考进度变化事件
        /// </summary>
        public event EventHandler<AIThinkingProgressEventArgs> ThinkingProgressChanged;

        /// <summary>
        /// AI移动完成事件
        /// </summary>
        public event EventHandler<AIMoveCompletedEventArgs> MoveCompleted;

        /// <summary>
        /// 当前AI
        /// </summary>
        public IAIAlgorithm CurrentAI => currentAI;

        /// <summary>
        /// 是否AI回合
        /// </summary>
        public bool IsAITurn => isAITurn;

        /// <summary>
        /// 最大思考时间（毫秒）
        /// </summary>
        public int MaxThinkingTime
        {
            get => maxThinkingTime;
            set => maxThinkingTime = Math.Max(100, Math.Min(30000, value)); // 限制在100ms到30秒之间
        }

        /// <summary>
        /// 设置AI难度
        /// </summary>
        /// <param name="difficulty">AI难度</param>
        public void SetAIDifficulty(AIDifficulty difficulty)
        {
            currentAI = AIFactory.CreateAI(difficulty);
        }

        /// <summary>
        /// 设置AI算法
        /// </summary>
        /// <param name="ai">AI算法</param>
        public void SetAI(IAIAlgorithm ai)
        {
            currentAI = ai;
        }

        /// <summary>
        /// 设置时间限制
        /// </summary>
        /// <param name="timeLimit">时间限制（毫秒）</param>
        public void SetTimeLimit(int timeLimit)
        {
            MaxThinkingTime = timeLimit;
        }

        /// <summary>
        /// 设置搜索深度
        /// </summary>
        /// <param name="depth">搜索深度</param>
        public void SetSearchDepth(int depth)
        {
            // 这里可以设置AI的搜索深度参数
            // 具体实现取决于AI算法
        }

        /// <summary>
        /// 开始AI回合
        /// </summary>
        /// <param name="board">当前棋盘状态</param>
        /// <param name="currentPlayer">当前玩家</param>
        public async void StartAITurn(PieceType[,] board, PieceType currentPlayer)
        {
            if (currentAI == null)
            {
                throw new InvalidOperationException("未设置AI算法");
            }

            isAITurn = true;

            try
            {
                // 启动进度监控
                var progressTask = MonitorThinkingProgress();
                var moveTask = currentAI.CalculateNextMoveAsync(board, currentPlayer, maxThinkingTime);

                // 等待AI计算完成
                var move = await moveTask;

                // 停止进度监控
                isAITurn = false;

                if (move != null)
                {
                    MoveCompleted?.Invoke(this, new AIMoveCompletedEventArgs { Move = move });
                }
            }
            catch (Exception ex)
            {
                isAITurn = false;
                throw new Exception($"AI计算移动时发生错误: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 停止AI回合
        /// </summary>
        public void StopAITurn()
        {
            isAITurn = false;
        }

        /// <summary>
        /// 重置AI状态
        /// </summary>
        public void Reset()
        {
            isAITurn = false;
            currentAI?.Reset();
        }

        /// <summary>
        /// 监控AI思考进度
        /// </summary>
        private async Task MonitorThinkingProgress()
        {
            while (isAITurn && currentAI != null)
            {
                var progress = currentAI.GetThinkingProgress();
                ThinkingProgressChanged?.Invoke(this, new AIThinkingProgressEventArgs { Progress = progress });

                await Task.Delay(100); // 每100ms检查一次进度
            }
        }

        /// <summary>
        /// 获取AI难度名称
        /// </summary>
        /// <returns>难度名称</returns>
        public string GetAIDifficultyName()
        {
            return currentAI != null ? AIFactory.GetDifficultyName(currentAI.Difficulty) : "未设置";
        }

        /// <summary>
        /// 获取AI难度描述
        /// </summary>
        /// <returns>难度描述</returns>
        public string GetAIDifficultyDescription()
        {
            return currentAI != null ? AIFactory.GetDifficultyDescription(currentAI.Difficulty) : "未设置AI";
        }
    }

    /// <summary>
    /// AI思考进度事件参数
    /// </summary>
    public class AIThinkingProgressEventArgs : EventArgs
    {
        public int Progress { get; set; }
    }

    /// <summary>
    /// AI移动完成事件参数
    /// </summary>
    public class AIMoveCompletedEventArgs : EventArgs
    {
        public Move Move { get; set; }
    }
} 